package com.guigui.gulimall.ware.listener;

import com.guigui.common.to.OrderTo;
import com.guigui.common.to.StockLockedTo;
import com.guigui.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "stock-release-stock-queue") // 库存释放队列
@Service
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 订单任务详情 解锁库存
     * @param stockLockedTo 订单任务详情id
     */
    @RabbitHandler
    public void stockLockedHandler(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unLockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }

    }

    /**
     * 订单解锁库存
     * @param order 订单
     */
    @RabbitHandler
    public void orderCloseHandler(OrderTo order, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unLockStock(order);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }


}
